package org.dingxf.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//声明配置类
//@Configuration
//@MapperScan(basePackages = "org.dingxf.dao2" , sqlSessionFactoryRef = "sqlSessionFactory")
public class SqlSessionFactoryBlogsConfig {

    //xml文件路径
    final String MAPPER_LOCATION = "org/dingxf/mapper2/*.xml";

    /**
     * 配置数据源
     */
    @Bean(name = "dataSourceBlogs")
    //读取配置文件
    @ConfigurationProperties(prefix = "spring.datasource-blogs")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSourceBlogs") DataSource dataSource) throws Exception {
        final MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();
    }

}
